/**
 * elancom Corporation copy right 2012 - 2015  
 *   
 * $Header$
 * $Id$
 * $Author$
 * $Date$
 * $Revision$
 */
package com.elancom.framework.component.internal;

import java.util.Iterator;

import com.elancom.framework.component.ComponentException;
import com.elancom.framework.component.Invocation;
import com.elancom.framework.component.InvocationContext;
import com.elancom.framework.component.ServiceReceiver;
import com.elancom.framework.component.interceptor.Interceptor;

/**
 * @author elancom
 * @date 2012-8-9
 */
public class DefaultInvocation implements Invocation {
	private boolean executed = false;

	private Iterator<Interceptor> iterator = null;

	private InvocationContext context;

	private ServiceReceiver serviceReceiver;

	/*
	 * (non-Javadoc)
	 * @see com.elancom.framework.component.Invocation#invoke()
	 */
	@Override
	public Object invoke() throws ComponentException {
		if (executed) {
			return null;
		}

		if (iterator != null) {
			while (iterator.hasNext()) {
				return iterator.next().intercept(this);
			}
		}

		try {
			if (serviceReceiver != null) {
				serviceReceiver.service(getContext().getInput(), getContext().getOutput());
			} else {
				// throw new
			}
			executed = true;
		} catch (Exception e) {
			e.printStackTrace();
			throw e;
		}

		return null;
	}

	/**
	 * @param context
	 */
	public DefaultInvocation(InvocationContext context) {
		super();
		this.context = context;
	}

	/*
	 * (non-Javadoc)
	 * @see com.elancom.framework.component.Invocation#getContext()
	 */
	@Override
	public InvocationContext getContext() {
		return context;
	}

	/**
	 * @return the iterator
	 */
	public Iterator<Interceptor> getIterator() {
		return iterator;
	}

	/**
	 * @param iterator
	 *            the iterator to set
	 */
	public void setIterator(Iterator<Interceptor> iterator) {
		this.iterator = iterator;
	}

	/**
	 * @return the serviceReceiver
	 */
	public ServiceReceiver getServiceReceiver() {
		return serviceReceiver;
	}

	/**
	 * @param serviceReceiver
	 *            the serviceReceiver to set
	 */
	public void setServiceReceiver(ServiceReceiver serviceReceiver) {
		this.serviceReceiver = serviceReceiver;
	}
}
